import Vue from "vue";
import VueRouter from "vue-router";
import store from "./store/";

Vue.use(VueRouter);

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
    if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
    return originalPush.call(this, location).catch(err => err);
}

// 创建一个路由器实例
const router = new VueRouter({
    mode: "hash",
    base: "__dirname",
    routes: [],
    // 设置滚动条位置
    scrollBehavior: to => {
        if (document.getElementById("con")) {
            if (to.meta.scrollTop)
                document.getElementById("con").scrollTop = to.meta.scrollTop;
            else document.getElementById("con").scrollTop = 0;
        }
    }
});

// 记录滚动条位置
function markScroll(to, from, next) {
    let whiteList = PUZZLE_CONFIG.whiteList;
    if (!sessionStorage.getItem('token') && to.path != "/login") {
        if (!whiteList.includes(to.path)) {
            router.push("/login");
            return;
        }
    }
    if (document.getElementById("con")) {
        from.meta.scrollTop = document.getElementById("con").scrollTop;
    }
    // 根据url打开标签
    let arr = JSON.parse(sessionStorage.getItem('tabList'))
    if (
        !from.name &&
        to.path != "/mainIndex" &&
        to.name &&
        PUZZLE_CONFIG.pageHome != to.name
    ) {
        if (arr && arr.length > 0) {
            const path = location.hash, tab = arr.filter(el => path.includes(el.path))[0]
            store.commit('SET_NOWTAB', tab);
            store.commit('SET_TAB', arr)
        }
    }
}

router.beforeEach((to, from, next) => {
    markScroll(to, from, next);
    next();
});
// 防止路由到错误地址
// router.beforeEach((to, from, next) => {
//   if (to.matched.length > 0)
//     next();
// });

// 错误捕获
// router.onError(err => { });

export default router;
